import { Dictionary } from '@/typings';

class SocketPlugin {
    public params: Dictionary;
    public websocket: WebSocket;
    public isConnect: boolean = false;
    public timeout: any = null;
    public isActivelyClose: boolean = false;
    constructor(parmas: Dictionary) {
        this.params = parmas;
        this.isConnect = false;
        this.isActivelyClose = false;
        this.timeout = null;
    }

    connect() {
        this.websocket = new WebSocket(this.params.url);
        this.initSocket(this.params);
    }
    initSocket(params) {
        this.isActivelyClose = false;

        this.websocket.onopen = () => {
            this.isConnect = true;
        };
        this.websocket.onerror = () => {
            console.log('WebSocket已断开');
            this.reconnectSocket();
        };
        this.websocket.onclose = () => {
            this.isConnect = false;
            // 如果手动关闭则不进行重连
            if (!this.isActivelyClose) {
                console.log('WebSocket已断开');
                this.reconnectSocket();
            }
        };
        this.websocket.onmessage = (e) => {
            params.callback(JSON.parse(e.data));
        };
    }
    reconnectSocket() {
        if (this.isConnect === true) return;
        this.isConnect = true;
        this.timeout && clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
            console.log('WebSocket已重新连接');
            this.connect();
            this.isConnect = false;
        }, 300000);
    }
    send(msg: Dictionary) {
        this.websocket.send(JSON.stringify(msg));
    }
    close() {
        this.isActivelyClose = true;
        if (this.websocket) {
            this.websocket.close();
        }
    }
}
export default SocketPlugin;
